import * as THREE from 'three'
import createApp from '../../core'
import { CSS2DRenderer, CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

function createEarthAndMoon (dom: HTMLElement) {
  const { camera, scene, update, renderer } = createApp(dom)

  renderer.shadowMap.enabled = true
  camera.position.set(-120, 100, 150)
  camera.lookAt(scene.position)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  const ambientLight = new THREE.AmbientLight(0xfffff)
  scene.add(ambientLight)

  const spotLight = new THREE.SpotLight(0xffffff, 2)
  spotLight.position.set(-200, 0, 0)
  spotLight.castShadow = true
  scene.add(spotLight)

  const loader = new THREE.TextureLoader()

  const earthGeo = new THREE.SphereGeometry(30, 32, 32)
  const earthMaterial = new THREE.MeshPhongMaterial()
  const earth = new THREE.Mesh(earthGeo, earthMaterial)
  earth.receiveShadow = true
  earth.castShadow = true
  scene.add(earth)
  import('@/assets/examples/earth.png').then(img => {
    loader.load(img.default, texture => {
      earthMaterial.map = texture
      earthMaterial.needsUpdate = true
    })
  })

  const moonGeo = new THREE.SphereGeometry(5, 32, 32)
  const moonMaterial = new THREE.MeshPhongMaterial()
  const moon = new THREE.Mesh(moonGeo, moonMaterial)
  moon.castShadow = true
  moon.receiveShadow = true
  scene.add(moon)
  import('@/assets/examples/moon.png').then(img => {
    loader.load(img.default, texture => {
      moonMaterial.map = texture
      moonMaterial.needsUpdate = true
    })
  })

  update((time: number) => {
    const angle = time / 2000
    moon.position.set(Math.sin(angle) * 100, 0, Math.cos(angle) * 100)
    moon.rotateY(0.02)
    earth.rotateY(0.01)
  })

  // 添加文字
  const earthDiv = document.createElement('div')
  earthDiv.className = 'label'
  earthDiv.innerText = 'earth'
  const earthText = new CSS2DObject(earthDiv)
  earthText.position.set(0, 35, 0)
  earth.add(earthText)

  const moonDiv = document.createElement('div')
  moonDiv.className = 'label'
  moonDiv.innerText = 'moon'
  const moonText = new CSS2DObject(moonDiv)
  moonText.position.set(0, 10, 0)
  moon.add(moonText)

  // 设置2D文字渲染器，可以添加div
  const css2Renderer = new CSS2DRenderer()
  css2Renderer.setSize(dom.offsetWidth, dom.offsetHeight)
  css2Renderer.domElement.style.position = 'absolute'
  css2Renderer.domElement.style.top = `${dom.offsetTop}px`
  css2Renderer.domElement.style.left = `${dom.offsetLeft}px`
  dom.appendChild(css2Renderer.domElement)

  // 由于CSS2D渲染器在Webgl渲染器之上，所以只需要把控制器添加到CSS2D渲染器上
  const orbitControls = new OrbitControls(camera, css2Renderer.domElement)
  console.log(orbitControls)
}

export {
  createEarthAndMoon
}
